import 'dart:io';
import 'dart:ui';

import 'package:android_id/android_id.dart';
import 'package:demo/common/i18n/my_translation.dart';
import 'package:demo/common/values/sp_keys.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:device_uuid/device_uuid.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../common/extension/ex_future.dart';
import 'env_config.dart';

/// 全局配置
class Config {
  static final Config _instance = Config._();

  factory Config() => _instance;

  Config._();

  String token = "";

  PackageInfo? _packageInfo;
  AndroidDeviceInfo? _androidDeviceInfo;
  IosDeviceInfo? _iosDeviceInfo;

  String _deviceId = "null";

  Locale locale = PlatformDispatcher.instance.locale;

  String _timezone = "null";

  final String _timezoneOffset = DateTime.now().timeZoneOffset.inHours.toString();

  init() async {
    _packageInfo = await PackageInfo.fromPlatform();

    var deviceInfoPlugin = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      _androidDeviceInfo = await deviceInfoPlugin.androidInfo;
      _deviceId = (await AndroidId().getId())?.toLowerCase() ?? 'null';
    } else {
      _iosDeviceInfo = await deviceInfoPlugin.iosInfo;
      _deviceId = await DeviceUuid().getUUID() ?? 'null';
    }

    _timezone = await safeAwait(FlutterTimezone.getLocalTimezone()) ?? "null";

    initLocale();
  }

  /// 应用名称
  String getAppName() {
    return _packageInfo?.appName ?? "";
  }

  /// 版本名称
  String getVersionName() {
    return _packageInfo?.version ?? "";
  }

  /// 版本号
  String getVersionCode() {
    return _packageInfo?.buildNumber ?? "";
  }

  /// 设备id
  String getDeviceId() {
    return _deviceId;
  }

  /// 国家代码
  String getCountryCode() {
    String countryCode = locale.countryCode ?? "null";
    switch (countryCode) {
      case "ID":
        countryCode = "IDN";
        break;
    }
    return countryCode;
  }

  /// 语言
  /// zh_cn en_us
  String getLanguage() {
    return locale.toString().toLowerCase();
  }

  /// 时区
  String getTimezone() {
    return _timezone;
  }

  /// 时区偏移 小时
  String getTimezoneOffset() {
    return _timezoneOffset;
  }

  void initLocale() {
    String langCode = SpKeys.langCode.getValue(defaultValue: locale.languageCode);

    // 查询用户语言是否支持
    locale =
        MyTranslation.supportedLang.firstWhereOrNull((element) {
          return langCode.startsWith(element.languageCode);
        }) ??
        MyTranslation.defaultLocal;

    // release 中文替换成英文
    if (locale.languageCode == "zh" && !envConfig.isDebug) {
      locale = MyTranslation.defaultLocal;
    }

    SpKeys.langCode.setValue(locale.languageCode);
  }

  /// 更改语言
  void updateLocale(Locale value) {
    locale = value;
    Get.updateLocale(value);
    SpKeys.langCode.setValue(locale.languageCode);
  }
}
